<%-- 
    Document   : role
    Created on : 2013-7-9, 15:39:36
    Author     : Danny Lee CMTI
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <title>角色权限管理</title>
        <%@include file="/WEB-INF/jspf/top_easyui.jspf" %>
        <script type="text/javascript" src="${contextPath}/easyui/plugins/datagrid-detailview.js"></script>
        <script type="text/javascript" >
            function modify(id) {
                $.ajax({
                    url: "${contextPath}/role/modify/ui.json?roleId=" + id,
                    success: function (data) {
                        var selected = $('#list_role').datagrid('getSelected');
                        if (selected) {
                            $('#add_bt').hide();
                            $('#update_bt').show();
                            $("#add_role_form").form('load', selected);
                            // 设置switchbutton checked状态
                            if (selected.status === 0)
                                $("#btnRoleStatus").switchbutton('check');
                            else
                                $("#btnRoleStatus").switchbutton('uncheck');
                            $('#add_dialog').dialog('setTitle', '修改角色信息');
                            $.each(data.list, function (i, v) {
                                var n = $("#role_Ul").tree('find', v.id);
                                if (n != null && $("#role_Ul").tree('isLeaf', n.target)) {
                                    $("#role_Ul").tree('check', n.target);
                                }
                            });
                            $('#add_dialog').dialog('open').dialog('hcenter');
                        }
                    }
                });
            }
            function showDetail(id) {
                $.ajax({
                    url: "${contextPath}/role/modify/ui.json?roleId=" + id,
                    success: function (data) {
                        var selected = $('#list_role').datagrid('getSelected');
                        if (selected) {
                            $('#add_dialog').dialog('setTitle', '查看角色信息');
                            $('#add_bt').hide();
                            $('#update_bt').hide();
                            $("#add_role_form").form('load', selected);
                            // 设置switchbutton checked状态
                            if (selected.status === 0)
                                $("#btnRoleStatus").switchbutton('check');
                            else
                                $("#btnRoleStatus").switchbutton('uncheck');
                            $.each(data.list, function (i, v) {
                                var n = $("#role_Ul").tree('find', v.id);
                                if (n != null && $("#role_Ul").tree('isLeaf', n.target)) {
                                    $("#role_Ul").tree('check', n.target);
                                }
                            });
                            $('#add_dialog').dialog('open').dialog('hcenter');
                            $("#btnRoleStatus").switchbutton('disable');
                            $('#add_role_form input,#add_role_form textarea').attr("disabled", true);
                        }
                    }
                });
            }
            function del(id) {
                var selected = $('#list_role').datagrid('getSelected');
                if (selected) {
                    //confirm(title,内容,当点击ok后的动作)
                    $.messager.confirm('友情提示', '你确定要删除角色名为 "' + selected.name + '" 的角色吗？', function (r) {
                        if (r) {
                            $.ajax({
                                type: "post",
                                url: "${contextPath}/role/delete.json?roleId=" + id,
                                success: function () {
                                    $.messager.alert("友情提示", "删除成功！", 'info');
                                    $('#list_role').datagrid('reload');
                                }
                            });
                        }
                    });
                }
            }
            function toLock(id) {
                var selected = $('#list_role').datagrid('getSelected');
                if (selected) {
                    if (selected.status == '0') {
                        //confirm(title,内容,当点击ok后的动作)
                        $.messager.confirm('友情提示', '你确定要冻结角色名为 "' + selected.name + '" 的角色吗？', function (r) {
                            if (r) {
                                $.ajax({
                                    type: "post",
                                    url: "${contextPath}/role/modify/lockRole.json?roleId=" + id + "&status=1",
                                    success: function () {
                                        $('#list_role').datagrid('reload');
                                    }
                                });
                            }
                        });
                    } else {
                        //confirm(title,内容,当点击ok后的动作)
                        $.messager.confirm('友情提示', '你确定要激活角色名为 "' + selected.name + '" 的角色吗？', function (r) {
                            if (r) {
                                $.ajax({
                                    type: "post",
                                    url: "${contextPath}/role/modify/lockRole.json?roleId=" + id + "&status=0",
                                    success: function () {
                                        $('#list_role').datagrid('reload');
                                    }
                                });
                            }
                        });
                    }
                }
            }
            $(document).ready(function () {
                var treeData;
                $('#list_role').datagrid({
                    // title:'角色列表', //标题  
                    method: 'post',
                    border: false,
                    //iconCls:'icon-tedit', //图标  
                    singleSelect: true, //多选  
                    fit: true,
                    fitColumns: true, //自动调整各列，用了这个属性，下面各列的宽度值就只是一个比例。  
                    striped: true, //奇偶行颜色不同  
                    //collapsible:true,//可折叠  
                    url: "${contextPath}/role/list/data.json", //数据来源  
                    //                      sortName: 'userNo', //排序的列  
                    //                      sortOrder: 'desc', //倒序  
                    idField: 'id', //主键字段  
                    pagination: true, //显示分页  
                    rownumbers: true, //显示行号
                    loadMsg: "正在加载，请稍候...", //远程加载时的提示信息
                    columns: [[
                            {field: 'oper', title: '操作', width: 150, align: 'center',
                                formatter: function (value, row, index) {
                                    var operContent = '';
            <shiro:hasPermission name="role:detail:*">
                                    operContent += '<a href="javascript:showDetail(' + row.id + ');" class="tdmenuImg"><img title="详情" src="${contextPath}/resources/css/icons/detail.png"/></a>';
            </shiro:hasPermission>
            <shiro:hasPermission name="role:modify:*">
                                    operContent += '<a href="javascript:modify(' + row.id + ');" class="tdmenuImg"><img title="修改" src="${contextPath}/resources/css/icons/pencil.png"/></a>';
            </shiro:hasPermission>
            <shiro:hasPermission name="role:delete:*">
                                    operContent += '<a href="javascript:del(' + row.id + ');" class="tdmenuImg"><img title="删除" src="${contextPath}/resources/css/icons/delete.png"/></a>';
            </shiro:hasPermission>
            <shiro:hasPermission name="role:modify:*">
                                    if (row.status == '0') {
                                        operContent = operContent + '<a href="javascript:toLock(' + row.id + ');" id="lock' + index + '" class="tdmenuImg"><img title="冻结" src="${contextPath}/resources/css/icons/lock.png"/></a>';
                                    } else {
                                        operContent = operContent + '<a href="javascript:toLock(' + row.id + ');" id="lock' + index + '" class="tdmenuImg"><img title="冻结" src="${contextPath}/resources/css/icons/key.png"/></a>';
                                    }
            </shiro:hasPermission>
                                    return operContent;
                                }
                            },
                            {field: 'name', title: '角色名称', width: 200, sortable: true},
                            {field: 'remark', title: '角色描述', width: 300, sortable: true},
                            {field: 'status', title: '状态', width: 150, sortable: true,
                                formatter: function (value, row, index) {
                                    if (value == '0') {
                                        return "激活";
                                    } else {
                                        return "冻结";
                                    }
                                }
                            }
                        ]],
                    //一下为subgrid
                    view: detailview,
                    detailFormatter: function (index, row) {
                        return '<div class="treePanel banner-color" style="padding:2px;height:205px;overflow-y:scroll"><img class="loadingImg" style="margin:5px" src="${contextPath}/resources/images/tree_loading.gif"/><ul id="sub' + index + '"></ul></div>';
                    },
                    onExpandRow: function (index, row) {
//                        console.log($('#sub' + index).html());
                        if ($.isEmptyObject($('#sub' + index).html())) {
                            $.ajax({
                                url: "${contextPath}/role/list/roleRight.json?roleId=" + row.id,
                                type: "get",
                                success: function (tree) {
                                    $('#sub' + index).tree({
                                        animate: true, data: tree.menu
                                        , onLoadSuccess: function () {
                                            $('#sub' + index).prev().hide();
                                        }
                                    });
                                }
                            });
                        }
                        $('#list_role').datagrid('fixDetailRowHeight', index);
                    },
                    onLoadSuccess: function () {
                        $(".treePanel").panel({
                            title: "角色菜单",
                            iconCls: 'icon-info',
                            border: true
                        });
                        var width = $(window).width() - 70;
                        $(".treePanel").panel('resize', {
                            width: width
                        });
                    },
                    onDblClickRow: function (rowIndex) {
                        modify(rowIndex);
                    }
                });

                var p = $('#list_role').datagrid('getPager');
                $(p).pagination({
                    pageList: [5, 10, 20, 30, 40, 50], //可以设置每页记录条数的列表 
                    beforePageText: '第', //页数文本框前显示的汉字 
                    afterPageText: '页    共 {pages} 页',
                    displayMsg: '当前显示 {from} - {to} 条记录   共 {total} 条记录'
                });
                //角色搜索searchBox
                $("#search_role").searchbox({
                    width: 240,
                    searcher: function (value, name) {//根据name搜索，value为搜索值
                        var params = $('#list_role').datagrid('options').queryParams; //先取得 datagrid 的查询参数
                        params[name] = value; //设置查询参数
                        $('#list_role').datagrid('load', params);
                    },
                    menu: '#rn',
                    prompt: '请输入搜索关键字'
                });
                $('#role_Ul').tree({
                    checkbox: true,
                    animate: true,
                    url: '${contextPath}/role/list/availableRights.json',
                    loadFilter: function (data) {
                        return data.tree;
                    }
                    //折叠全部节点
                    , onLoadSuccess: function () {
                        $(this).tree("collapseAll");
                    }
                });
                function addOrUpdate(url) {
                    var nodes = $('#role_Ul').tree('getChecked');
                    nodes = nodes.concat($('#role_Ul').tree('getChecked', 'indeterminate'));
                    var s = new Array();
                    for (var i = 0; i < nodes.length; i++) {
                        s.push(nodes[i].id);
                    }
                    var ids = s.join();
                    //保存角色
                    $('#right_Ids').val(ids);
                    var upOptions = {//表单提交前的配置（jquery-form）
                        url: url, //即action地址
                        type: "POST",
                        dataType: "json",
                        beforeSubmit: function () {
                            if (nodes === "" || nodes === null) {
                                $.messager.alert('系统提示', '请选择权限！', 'warning');
                                return false;
                            }
                            return $("#add_role_form").form('validate');//返回表单验证是否成功，成功返回true，表单进行提交，失败返回false，表单无法提交
                        },
                        //表单提交成功后执行
                        success: function (data) {//提交成功后执行的操作，addData（形参，可任意取名）为返回的json，
                            if (data.result) {
                                $.messager.alert('友情提示', '保存成功！', 'info');
                                $('#add_dialog').dialog('close');
                                $('#list_role').datagrid('reload');
                            } else {
                                $.messager.alert('友情提示', '保存失败！<br>' + data.msg, 'error');
                            }
                        }
                    };
                    $("#add_role_form").ajaxSubmit(upOptions);//表单进行提交，带上option参数，提交成功后完成option里的动作
                }
                $("#add_dialog").dialog({
                    title: "角色信息",
                    iconCls: "icon-person",
                    closed: true,
                    modal: true,
                    maximizable: true,
                    shadow: false,
                    width: 450, height: 500, top: 20,
                    buttons: [{
                            id: 'add_bt',
                            text: '保存',
                            iconCls: 'icon-save',
                            handler: function () {//保存时的动作
                                addOrUpdate("${contextPath}/role/add/action.json");
                            }
                        }, {
                            id: 'update_bt',
                            text: '修改',
                            iconCls: 'icon-fileupdate',
                            handler: function () {//修改时的动作
                                addOrUpdate("${contextPath}/role/modify/action.json");
                            }
                        }, {
                            text: '取消',
                            handler: function () {
                                $('#add_dialog').dialog('close');
                            }
                        }],
                    onOpen: function () {
//                        $('#role_Ul_panel').panel('header').addClass('top-border');
                    },
                    onClose: function () {
                        $('#add_role_form input,#add_role_form textarea').attr("disabled", false);
                        $("#btnRoleStatus").switchbutton('enable');
                    },
                    onBeforeClose: function () {
                        $("#add_role_form").form('clear');
                        //将角色表Checked属性去除
                        $('#role_Ul').tree('reload');
                        //将switchbutton重置为checked状态
                        $("#btnRoleStatus").switchbutton('check');
                    },
                    onMaximize: function () {
                        var width = $(window).width();
                        var height = $(window).height();
                        //最dialog最大化前设置form_box的高度
                        $('#form_box').height(height - 76);
                        $('#form_box').layout('resize', {
                            width: width,
                            height: height
                        });
                    },
                    onRestore: function () {
                        $('#form_box').height(340);
                        $('#form_box').layout('resize', {
                            width: '100%',
                            height: 340
                        });
                    }
                });
                $("#btnRoleStatus").switchbutton({
                    checked: true,
                    onChange: function (checked) {
//                        console.log(checked);
                        if (checked) {
                            $("#roleStatus").val(0);
                        } else {
                            $("#roleStatus").val(1);
                        }
                    }
                });
                $("#addRole").click(function () {
                    $.ajax({
                        url: "${contextPath}/role/add/ui.json",
                        success: function () {
                            $('#add_bt').show();
                            $('#update_bt').hide();
                            $('#add_dialog').dialog('open').dialog('hcenter');
                            $('#add_dialog').dialog('setTitle', '角色信息');
                        }
                    });
                });
                // 注册全局ajax错误处理函数
                $(document).ajaxError(new jQueryAjaxErrorHandler());
            });
        </script>
    </head>
    <body class="easyui-layout">
        <script type="text/javascript">
            $("body").mask({
                maskMsg: '<div class="loading_text"><img src="${contextPath}/resources/images/loading_2.gif"/><span>正在初始化，请稍后...</span></div>',
                opacity: 1
            });
            $(function () {
                $("body").mask('hide');
            })
        </script>
        <div region="north" data-options="border:false" class="bottom-border" style="height: 42px; padding-top: 0px;padding-left: 2px">
            <div id="roleSearchBar">
                <table>
                    <tr>
                        <td style="padding:3px 6px 0 3px">
                            <input id="search_role" />
                        </td>
                        <shiro:hasPermission name="role:add:*">
                            <td style="padding-top:5px"><div class="datagrid-btn-separator"></div></td>
                            <td  style="padding-top:3px">
                                <a href="Javascript:void(0)" id="addRole" class="easyui-linkbutton" iconCls="icon-add" plain="true">添加角色</a>
                            </td>
                        </shiro:hasPermission>
                    </tr>
                </table>
                <div id="rn" style="width:120px">
                    <div name="name">角色名称</div> 
                </div> 
            </div>
        </div>
        <div id="mainContainer" region="center" data-options="border:false"  title="" style="padding:0px;background:#eee;" class="bottom-border">
            <table  id="list_role" cellspacing="0" cellpadding="0"> 
            </table>
        </div>
        <div id="add_dialog" class="easyui-dialog" >
            <div id="form_box" class="easyui-layout"  style="height:370px;" data-options="fit:true">  
                <div data-options="region:'north',title:'基本信息',iconCls:'icon-form',border:false,collapsible:false" style="height:140px; padding:8px;border-bottom-width: 1px">
                    <form method="POST" id="add_role_form" >
                        <input type='hidden' name='id'/>
                        <input type="hidden" name="rightIds" id="right_Ids"/>
                        <div style="margin-bottom: 8px">
                            <input class="easyui-textbox" data-options="label:'角色名称：',width:300,required:true,validType:'validateAccount'" name="name" />
                            <span style="margin-left: 35px">
                                <input class="easyui-switchbutton" id="btnRoleStatus" data-options='onText:"激活",offText:"冻结",width:80'/>
                                <input type="hidden" id="roleStatus" name="status" value="0"/>
                            </span>
                        </div>
                        <div>
                            <textarea class="easyui-textbox" data-options="multiline:true,label:'角色描述：'" name="remark" style="width:420px;height: 50px"></textarea>
                        </div>

                    </form>
                </div>
                <div data-options="region:'center',title:'权限设置',iconCls:'icon-node-tree',border:false" id="role_Ul_panel" style="padding-left: 10px; padding-top: 10px; height: 200px;">
                    <ul id="role_Ul">
                    </ul>
                </div> 
            </div>   
        </div>

    </body>
</html>
